import lamejs from "lamejs";

export class Broadcast {
  speech(text) {
    const msg = new SpeechSynthesisUtterance();
    msg.text = text;
    msg.volume = "1"; // 声音的音量，区间范围是0到1，默认是1。
    msg.rate = "1"; // 语速，数值，默认值是1，范围是0.1到10，表示语速的倍数，例如2表示正常语速的两倍。
    msg.pitch = "2"; // 表示说话的音高，数值，范围从0（最小）到2（最大）。默认值为1。
    msg.lang = "zh-cn"; // 使用的语言，字符串， 例如："zh-cn"
    return msg;
  }
  play = (text) => {
    speechSynthesis.speak(this.speech(text));
  };
  stop = (text) => {
    speechSynthesis.cancel(this.speech(text));
  };
}
// 时间戳转字符串 生成’yyyy/MM/dd 上(下)午hh:mm:ss '格式,差了八小时，弃用；用transTimestamp方法
export function getLocalTime(n) {
  console.log(new Date(parseInt(n)));
  return new Date(parseInt(n)).toLocaleString().replace(/:\d{1,2}$/, " ");
}
/**
 * UTC时间转换
 * @returns {string}
 * @param datetime UTC时间
 * @param dateSeprator 日期拼接符
 * @param timeSeprator 时间拼接符
 * @Eexample dateFormat("2021-09-03T22:42:05.659+00:00", "/", ":")
 *           dateFormat("2021-09-03T22:42:05.659+00:00")
 */
export function transTimestamp(
  datetime,
  dateSeprator = "/",
  timeSeprator = ":"
) {
  if (datetime) {
    const date = new Date(datetime);
    const year = `${date.getFullYear()}`;
    let month = `${date.getMonth() + 1}`;
    let day = `${date.getDate()}`;
    let hour = `${date.getHours()}`;
    let minute = `${date.getMinutes()}`;
    let second = `${date.getSeconds()}`;

    if (month.length === 1) {
      month = `0${month}`;
    }
    if (day.length === 1) {
      day = `0${day}`;
    }
    if (day.length === 1) {
      day = `0${day}`;
    }
    if (hour.length === 1) {
      hour = `0${hour}`;
    }
    if (minute.length === 1) {
      minute = `0${minute}`;
    }
    if (second.length === 1) {
      second = `0${second}`;
    }
    return `${year}${dateSeprator}${month}${dateSeprator}${day} ${hour}${timeSeprator}${minute}${timeSeprator}${second}`;
  }
}
// 两数组根据key对比，去重
/**
 *
 * @param {array[json]} list1
 * @param {array[json]} list2 需要去重的数组
 * @param {string} key
 * @returns list2去重list1后的结果
 */
export const compareArr = function (list1, list2, key) {
  const result = list2.filter(function (item1) {
    return list1.every(function (item2) {
      return item2[key] !== item1[key];
    });
  });
  return result;
};

export const wavToMp3 = function (recorderData) {
  // new Int16Array(this.recorder.getWAV().buffer) 取录音的buffer
  const channels = 1; //1 单声道 2 立体声
  //const sampleRate = 44100; //44.1khz
 // const kbps = 128; //128kbps mp3
    const sampleRate = 22050;
    const kbps = 32;
  var mp3encoder = new lamejs.Mp3Encoder(channels, sampleRate, kbps);
    var mp3Data = [];
    const originalLength = recorderData.buffer.byteLength;
    var samples;
    if (originalLength % 2 !== 0) {
        const adjustedData = new Int8Array(originalLength + 1);
        const int8=new Int8Array(recorderData.buffer)
        for (let i = 0; i < originalLength; i = i + 1) {
            adjustedData[i] = int8[i];
        }
        adjustedData[originalLength] = 0; // Use zero-padding
        samples = new Int16Array(adjustedData);
    } else {
        samples = new Int16Array(recorderData.buffer);
    }
  const sampleBlockSize = 1152; //576的倍数
  for (var i = 0; i < samples.length; i += sampleBlockSize) {
    var sampleChunk = samples.subarray(i, i + sampleBlockSize);
    const mp3buf = mp3encoder.encodeBuffer(sampleChunk);
    if (mp3buf.length > 0) {
      mp3Data.push(mp3buf);
    }
  }
  var mp3buf = mp3encoder.flush(); //finish writing mp3
  if (mp3buf.length > 0) {
    mp3Data.push(new Int8Array(mp3buf));
  }
  var blob = new Blob(mp3Data, { type: "audio/mp3" });
  return blob;
};

export const savePicture = (url,filename,fn) => {
  // 创建Image对象
  const img = new Image();

  // 设置图片地址
  img.src = url;
  img.setAttribute("crossOrigin", "anonymous");  //添加srossOrigin属性，解决跨域问题

  // 等待图片加载完成
  img.onload = () => {
    // 创建Canvas对象
    const canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // 将图片绘制到Canvas上
    const ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // 获取图片的Base64编码
    const dataURL = canvas.toDataURL("image/png");

    // 创建下载链接
    const link = document.createElement("a");
    link.href = dataURL;
    link.download = filename;

    // 触发下载链接的click事件
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    fn()
  };
};